let md5 = require('md5')

let sign = function(obj) {
    let  {appid, body, mch_id, nonce_str, notify_url,openid, out_trade_no, spbill_create_ip, total_fee, trade_type, key} = obj
    let key1 = key
    delete obj.key
    let str = raw(obj)
    let strTemp = str + `&key=${key1}`
  let signStr = md5(strTemp)
  let strUpper =signStr.toUpperCase()
  return strUpper
}


function formatMessage(result) {

    let message = {};
    if (typeof result === 'object') {
        let keys = Object.keys(result);

        for (let i=0; i< keys.length; i++) {
            let item = result[keys[i]];
            let key = keys[i];

            if (!(item instanceof Array) || item.length === 0) {
                if (typeof item === 'object') {
                    message[key] = formatMessage(item);
                }else {
                    message[key] = (item || '').trim();
                }
                continue;
            }

            if (item.length === 1) {
                let val = item[0];

                if (typeof val === 'object') {
                    message[key] = formatMessage(val);
                }else {
                    message[key] = (val || '').trim();
                }
            }else {
                message[key] = [];

                for (let j= 0; j< item.length; j++) {
                    message[key].push(formatMessage(item[j]));
                }
            }
        }
    }

    return message;
};

function paySign ({ appid, nonceStr, prepay_id, timeStamp, key}) {
    let str = `appId=${appid}&nonceStr=${nonceStr}&package=${prepay_id}&signType=MD5&timeStamp=${timeStamp}&key=${key}`
    let signStr = md5(str)
    return signStr

}
module.exports = {
    sign,
    formatMessage,
    paySign
}

function raw(args) {
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function(key) {
        newArgs[key.toLowerCase()] = args[key];
    });

    var str = '';
    for(var k in newArgs) {
        str += '&' + k + '=' + newArgs[k];
    }
    str = str.substr(1);
    return str;
};
